package gatperdut.chato.core.interpreter.actions;

import gatperdut.chato.constants.CSConstantsCommandResult.CommandExecutionResult;
import gatperdut.chato.constants.CSConstantsLanguages;
import gatperdut.chato.constants.CSConstantsString;
import gatperdut.chato.core.characters.BaseController;
import gatperdut.chato.core.interpreter.actions.generic.Action;
import gatperdut.chato.core.interpreter.grammar.comminfo.SpeakInfo;
import gatperdut.chato.model.Chato.Constant.Language;

import java.util.List;

public class SpeakAction extends Action {

    public SpeakAction( SpeakInfo info, BaseController entityController ) {
        super( info, entityController );
    }

    @Override
    public CommandExecutionResult perform() {
        checkForRunningCraft();

        if ( getInfo().getLanguage() == null ) { // --which langs can I speak?
            StringBuilder sb = new StringBuilder( "You can speak the following languages:" + CSConstantsString.NEWLINE );
            List<Language> knownLanguages = getEntityController().getCharacter().getKnownLanguages();
            int n = 0;
            for ( Language l : knownLanguages ) {
                n++;
                sb.append( CSConstantsLanguages.getLanguageAliasesString( l ) );
                if ( n < knownLanguages.size() ) {
                    sb.append( CSConstantsString.NEWLINE );
                }
            }
            sb.append( CSConstantsString.NEWLINE + "You are currently speaking in "
                    + CSConstantsLanguages.getLanguageAliasesString( getEntityController().getCharacter().getCurrentLanguage() ) + "." );
            getEntityController().tx( sb.toString() );
            return CommandExecutionResult.OK;
        }

        // --change language.
        Language l = CSConstantsLanguages.getLanguageFromString( getInfo().getLanguage() );
        if ( l == null ) {
            getEntityController().tx( "That language does not exist." );
            return CommandExecutionResult.OK;
        }
        if ( !getEntityController().getCharacter().getKnownLanguages().contains( l ) ) {
            getEntityController().tx( "You do not know that language." );
            return CommandExecutionResult.OK;
        }

        if ( getEntityController().getCharacter().getCurrentLanguage() == l ) {
            getEntityController().tx( "You are already speaking in " + CSConstantsLanguages.getLanguageAliasesString( l ) + "." );
            return CommandExecutionResult.OK;
        }

        getEntityController().getCharacter().setCurrentLanguage( l );

        getEntityController().tx( "You start speaking in " + CSConstantsLanguages.getLanguageAliasesString( l ) + "." );

        return CommandExecutionResult.OK;
    }

    @Override
    public SpeakInfo getInfo() {
        return (SpeakInfo) super.getInfo();
    }

    @Override
    public boolean interruptsCrafting() {
        return true;
    }

}
